package com.ynny.chapter04.common;

import com.ynny.chapter04.exception.UserNotFoundException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleValidException(MethodArgumentNotValidException e) {
        HashMap<Object, Object> map = new HashMap<>();

        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }

        return AjaxResult.error(400, "参数校验异常：")
                .put("errors",map);
    }

    @ExceptionHandler(UserNotFoundException.class)
    public AjaxResult handleException(UserNotFoundException e) {

        return AjaxResult.error(400, "用户不存在：")
                .put("data",e.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {

        return AjaxResult.error(500, "系统异常：")
                .put("message",e.getMessage());
    }


}

